package org.rayson.server;

import java.nio.channels.ClosedChannelException;
import java.util.Properties;

import org.rayson.api.exception.ProtocolException;
import org.rayson.api.server.ServerRequest;
import org.rayson.api.server.ServerResponse;
import org.rayson.api.server.exception.ServiceException;
import org.rayson.server.rpc.ServerRequestImpl;

public class Worker implements Manager, Runnable {

	private final Container container;

	private boolean running;

	private Thread thread;

	private final long id;

	public Worker(final long workerId, final Container container) {
		super();
		this.id = workerId;
		this.container = container;
	}

	@Override
	public Container getContainer() {
		return container;
	}

	@Override
	public String getName() {
		return "Worker " + id + " of" + container;
	}

	private void handleRequest(final ServerRequest request)
			throws ClosedChannelException, ServiceException, ProtocolException {
		final ServerResponse response = this.container.getServiceManager()
				.invoke(request);
		// Add response to connection.
		((ServerRequestImpl) request).getConnection().addResponse(response);
	}

	@Override
	public void run() {
		while (running) {
			try {
				final ServerRequest request = this.container
						.getRequestManager().take();
				try {
					handleRequest(request);
				} catch (final ClosedChannelException | ServiceException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (final ProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (final InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	@Override
	public void start(final Properties properties) throws Exception {
		running = true;
		thread = new Thread(this, getName());
		thread.start();
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub

	}
}